"use client"

import { useState, useCallback, useRef } from "react"
import { useDropzone } from "react-dropzone"
import { Upload, ArrowDownToLine, RefreshCw, ChevronDown } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader } from "@/components/ui/card"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { ThemeToggle } from "@/components/theme-toggle"
import Image from "next/image"

// 使用真实API替换模拟函数
const recognizeDishes = async (file: File) => {
  try {
    const formData = new FormData();
    formData.append('image', file);

    // 打印请求参数
    console.log("请求参数:");
    formData.forEach((value, key) => {
      console.log(`${key}:`, value);
    });
    
    const response = await fetch('/api/recognize-dish', {
      method: 'POST',
      body: formData,
    });
    
    if (!response.ok) {
      throw new Error('识别请求失败');
    }
    
    const data = await response.json();
    return data.dishes || [];
  } catch (error) {
    console.error('菜品识别出错:', error);
    return ['识别失败，请重试'];
  }
}

// 案例菜单
const 案例菜单 = [
  { id: "1", 名称: "红烧狮子头", 描述: "肉质鲜嫩，口感丰富的传统名菜", 图片链接: "/01.jpg" },
  { id: "2", 名称: "糖醋排骨", 描述: "酸甜可口，色泽诱人的经典菜式", 图片链接: "02.jpg" },
  { id: "3", 名称: "麻婆豆腐", 描述: "麻辣鲜香，令人回味无穷的川菜代表", 图片链接: "/03.jpg" },
  { id: "4", 名称: "宫保鸡丁", 描述: "鸡肉嫩滑，花生香脆，口感丰富多样", 图片链接: "/04.jpg" },
  { id: "5", 名称: "水煮鱼", 描述: "鱼肉鲜嫩，麻辣爽口的四川名菜", 图片链接: "/05.jpg" },
  { id: "6", 名称: "东坡肉", 描述: "肥而不腻，入口即化的杭州名菜", 图片链接: "/06.jpg" },
]

export default function AIMenuGenerator() {
  const [dishes, setDishes] = useState<string[]>([])
  const [uploadedImage, setUploadedImage] = useState<string | null>(null)
  const [originalFile, setOriginalFile] = useState<File | null>(null)
  const [isReidentifying, setIsReidentifying] = useState(false)
  const imageRef = useRef<HTMLImageElement>(null)

  const processFile = useCallback(async (file: File) => {
    const imageUrl = URL.createObjectURL(file)
    setUploadedImage(imageUrl)
    setOriginalFile(file)

    setIsReidentifying(true)
    const recognizedDishes = await recognizeDishes(file)
    setDishes(recognizedDishes)
    setIsReidentifying(false)
  }, [])

  const onDrop = useCallback(
    async (acceptedFiles: File[]) => {
      const file = acceptedFiles[0]
      if (file) {
        await processFile(file)
      }
    },
    [processFile],
  )

  const { getRootProps, getInputProps, isDragActive, open } = useDropzone({ onDrop, noClick: true })

  const handleReidentify = async () => {
    if (originalFile) {
      setIsReidentifying(true)
      if (imageRef.current) {
        imageRef.current.classList.add("animate-spin")
      }
      const recognizedDishes = await recognizeDishes(originalFile)
      setDishes(recognizedDishes)
      setIsReidentifying(false)
      if (imageRef.current) {
        imageRef.current.classList.remove("animate-spin")
      }
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-background to-secondary/20">
      <header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
        <div className="container flex h-14 items-center">
          <div className="mr-4 hidden md:flex">
            <a className="mr-6 flex items-center space-x-2" href="/">
              <span className="hidden font-bold sm:inline-block">AI菜单图片生成器</span>
            </a>
            <nav className="flex items-center space-x-6 text-sm font-medium">
              <a className="transition-colors hover:text-foreground/80 text-foreground/60" href="#features">
                功能
              </a>
              <a className="transition-colors hover:text-foreground/80 text-foreground/60" href="#examples">
                案例
              </a>
              <a className="transition-colors hover:text-foreground/80 text-foreground/60" href="#pricing">
                定价
              </a>
            </nav>
          </div>
          <div className="flex flex-1 items-center justify-between space-x-2 md:justify-end">
            <div className="flex flex-1 items-center justify-end space-x-2">
              <div className="w-full flex-1 md:w-auto md:flex-none">
                <button className="inline-flex items-center rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2 relative w-full justify-start text-sm text-muted-foreground sm:pr-12 md:w-40 lg:w-64">
                  <span className="hidden lg:inline-flex">搜索文档...</span>
                  <span className="inline-flex lg:hidden">搜索...</span>
                  <kbd className="pointer-events-none absolute right-1.5 top-1.5 hidden h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 sm:flex">
                    <span className="text-xs">⌘</span>K
                  </kbd>
                </button>
              </div>
              <ThemeToggle />
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="icon">
                    <ChevronDown className="h-4 w-4" />
                    <span className="sr-only">更多选项</span>
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem>账户设置</DropdownMenuItem>
                  <DropdownMenuItem>支持</DropdownMenuItem>
                  <DropdownMenuItem>许可证</DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
        </div>
      </header>

      <main className="container mx-auto p-8 font-sans">
      <h1 className="text-4xl font-extrabold tracking-tight lg:text-5xl text-center mb-4">AI美食菜单生成器</h1>
        <p className="text-xl text-muted-foreground text-center mb-8">
            上传您的菜品图片，让AI为您创造令人垂涎的菜单展示
          </p>
        <div className="max-w-4xl mx-auto">
          <div
            {...getRootProps()}
            className={`border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-all relative ${
              isDragActive
                ? "border-indigo-500 bg-indigo-50"
                : "border-gray-300 hover:border-indigo-300 hover:bg-indigo-50"
            }`}
          >
            <input {...getInputProps()} />
            <Upload className="mx-auto h-12 w-12 text-gray-400" />
            {isDragActive ? (
              <p className="mt-4 text-indigo-500 text-lg">放开鼠标，上传图片 ...</p>
            ) : (
              <>
                <p className="mt-4 text-gray-500 text-lg">将图片拖放到此处</p>
                <Button onClick={open} className="mt-4 bg-black text-white hover:bg-gray-800">
                  选择文件
                </Button>
              </>
            )}
          </div>
        </div>

        {uploadedImage && (
          <div className="mt-12 bg-white rounded-xl shadow-lg overflow-hidden transition-all hover:shadow-xl max-w-4xl mx-auto">
            <div className="md:flex">
              <div className="md:flex-shrink-0 relative">
                <img
                  ref={imageRef}
                  src={uploadedImage || "/placeholder.svg"}
                  alt="上传的菜品图像"
                  className="h-64 w-full object-cover md:w-64 transition-all duration-500 ease-in-out"
                />
                {isReidentifying && (
                  <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
                    <RefreshCw className="w-12 h-12 text-white animate-spin" />
                  </div>
                )}
              </div>
              <div className="p-8 flex-grow">
                <h3 className="text-2xl font-semibold mb-3 text-gray-800">识别结果</h3>
                {isReidentifying ? (
                  <p className="text-gray-600 mb-6">正在重新识别菜品，请稍候...</p>
                ) : dishes.length > 0 ? (
                  <>
                    <p className="text-gray-600 mb-4">AI 识别到以下菜品：</p>
                    <ul className="list-disc list-inside text-gray-700 mb-6">
                      {dishes.map((dish, index) => (
                        <li key={index}>{dish}</li>
                      ))}
                    </ul>
                  </>
                ) : (
                  <p className="text-gray-600 mb-6">正在识别菜品，请稍候...</p>
                )}
                <div className="flex justify-between">
                  <button
                    onClick={handleReidentify}
                    className={`flex items-center px-4 py-2 rounded-md transition-colors ${
                      isReidentifying
                        ? "bg-gray-200 text-gray-500 cursor-not-allowed"
                        : "bg-indigo-100 text-indigo-700 hover:bg-indigo-200"
                    }`}
                    disabled={isReidentifying}
                  >
                    <RefreshCw className={`w-5 h-5 mr-2 ${isReidentifying ? "animate-spin" : ""}`} />
                    重新识别
                  </button>
                  <a
                    href={uploadedImage}
                    download={originalFile?.name || "uploaded-image"}
                    className="flex items-center px-4 py-2 bg-green-100 text-green-700 rounded-md hover:bg-green-200 transition-colors"
                  >
                    <ArrowDownToLine className="w-5 h-5 mr-2" />
                    下载原图
                  </a>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* New: Menu to image generation examples */}
        <div className="mt-16">
          <h2 className="text-2xl font-bold mb-6 text-center">菜单生成案例</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {案例菜单.map((菜品) => (
              <Card key={菜品.id} className="overflow-hidden">
                <CardHeader className="p-0">
                  <div className="relative aspect-video">
                    <Image src={菜品.图片链接 || "/placeholder.svg"} alt={菜品.名称} layout="fill" objectFit="cover" />
                  </div>
                </CardHeader>
                <CardContent className="p-4">
                  <h3 className="font-bold text-lg mb-2">{菜品.名称}</h3>
                  <p className="text-sm text-muted-foreground">{菜品.描述}</p>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </main>

      <footer className="border-t py-12 bg-gradient-to-r from-primary/10 via-secondary/10 to-primary/10">
        <div className="container mx-auto px-4">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            <div>
              <h3 className="text-lg font-semibold mb-4">关于我们</h3>
              <p className="text-sm text-muted-foreground">
                AI美食菜单生成器致力于为餐厅提供创新的菜单设计解决方案，让您的菜单更具吸引力。
              </p>
            </div>
            <div>
              <h3 className="text-lg font-semibold mb-4">快速链接</h3>
              <nav className="flex flex-col space-y-2 text-sm">
                <a href="#" className="hover:text-primary transition-colors">
                  首页
                </a>
                <a href="#" className="hover:text-primary transition-colors">
                  功能
                </a>
                <a href="#" className="hover:text-primary transition-colors">
                  定价
                </a>
                <a href="#" className="hover:text-primary transition-colors">
                  联系我们
                </a>
              </nav>
            </div>
            <div>
              <h3 className="text-lg font-semibold mb-4">法律</h3>
              <nav className="flex flex-col space-y-2 text-sm">
                <a href="#" className="hover:text-primary transition-colors">
                  隐私政策
                </a>
                <a href="#" className="hover:text-primary transition-colors">
                  使用条款
                </a>
                <a href="#" className="hover:text-primary transition-colors">
                  Cookie 政策
                </a>
              </nav>
            </div>
            <div>
              <h3 className="text-lg font-semibold mb-4">联系我们</h3>
              <p className="text-sm text-muted-foreground mb-2">邮箱：info@aimenu.com</p>
              <p className="text-sm text-muted-foreground">电话：+86 123 4567 8900</p>
            </div>
          </div>
          <div className="mt-8 pt-8 border-t text-center text-sm text-muted-foreground">
            © 2024 AI美食菜单生成器. 保留所有权利.
          </div>
        </div>
      </footer>
    </div>
  )
}

